package com.ontheroad.controller;

import cn.modoumama.page.GridDataModel;
import com.ontheroad.core.annotation.QiniuUploadToken;
import com.ontheroad.core.util.SpringSecurityUtils;
import com.ontheroad.core.web.BaseController;
import com.ontheroad.news.model.NewsModel;
import com.ontheroad.news.service.NewsService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Map;

/**
 * Created by kedong on 2017/12/9 0009.
 */
@Controller
@RequestMapping("/news")
public class NewsController extends BaseController {

    private Logger log = LoggerFactory.getLogger(getClass());

    @Autowired
    private NewsService newsService;

    @Value("${context_url}")
    private String contextUrl;


    @RequestMapping("list")
    public String list() {
        return "news/list";
    }


    @RequestMapping("getData")
    @ResponseBody
    public GridDataModel getdata(HttpServletRequest request) {
        return getGridData(request, newsService);
    }

    @QiniuUploadToken
    @RequestMapping("add")
    public String add() {
        return "news/add";
    }

    @RequestMapping("save")
    public String save(NewsModel model, HttpServletRequest request) {
        model.setCreateId(SpringSecurityUtils.getCurrentUser().getUserId().intValue());
        model.setCreateTime(new Date());
        model = newsService.save(model);
        model.setUrl(contextUrl + "/news/detail?id=" + model.getId());
        newsService.updateById(model);
        return "success";
    }

    @QiniuUploadToken
    @RequestMapping("edit")
    public String edit(Map map, Integer id) {
        NewsModel news = newsService.findById(id);
        map.put("news", news);
        return "news/edit";
    }


    @RequestMapping("detail")
    public String detail(Map map, Integer id) {
        NewsModel news = newsService.findById(id);
        map.put("news", news);
        return "news/detail";
    }


    @RequestMapping("update")
    public String update(NewsModel model) {
        if (model.getId() == null) {
            return "success";
        }
        model.setUpdateTime(new Date());
        model.setUrl(contextUrl + "/news/detail?id=" + model.getId());
        newsService.updateById(model);
        return "success";
    }


}
